package v1

import (
	"bc/service"
	"bc/util"
	"bc/util/library/zstack"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"strconv"
)

type image struct {

}
func (t *image) Create(c *gin.Context){

	m := make(map[string]map[string]interface{})
	m["params"] = make(map[string]interface{})

	if v,ok := c.GetPostForm("name");ok{
		m["params"]["name"] = v
	}
	if v,ok := c.GetPostForm("desc");ok{
		m["params"]["description"] = v
	}
	if v,ok := c.GetPostForm("url");ok{
		m["params"]["url"] = v
	}
	if v,ok := c.GetPostForm("mediaType");ok{
		//镜像类型
		//value : [RootVolumeTemplate,DataVolumeTemplate]
		m["params"]["mediaType"] = v
	}
	if v,ok := c.GetPostForm("guestOsType");ok{
		//镜像对应客户机操作系统类型
		m["params"]["guestOsType"] = v
	}
	if v,ok := c.GetPostForm("system");ok{
		//是否系统镜像
		m["params"]["system"] = v
	}
	if v,ok := c.GetPostForm("format");ok{
		//镜像格式
		m["params"]["format"] = v
	}
	if v,ok := c.GetPostForm("platform");ok{
		//镜像的系统平台
		//values:[Linux,Windows,WindowsVirtio,Other,Paravirtualization]
		m["params"]["platform"] = v
	}
	/*
	if v,ok := c.GetPostFormArray("backupStorageUuids");ok{
		//指定添加镜像的镜像服务器UUID列表
		//values:[]
		m["params"]["backupStorageUuids"] = v
	}*/
	m["params"]["backupStorageUuids"] = []string{"c7196d2e795f44f99e9953401652c17b"}

	if v,ok := c.GetPostForm("type");ok{
		//
		m["params"]["type"] = v
	}
	if v,ok := c.GetPostForm("resourceUuid");ok{
		//资源UUID。若指定，镜像会使用该字段值作为UUID
		m["params"]["resourceUuid"] = v
	}
	if v,ok := c.GetPostFormArray("systemTags");ok{
		//系统标签
		m["params"]["systemTags"] = v
	}
	if v,ok := c.GetPostFormArray("userTags");ok{
		//用户标签
		m["params"]["userTags"] = v
	}
	byt,err := json.Marshal(&m)
	if err !=nil {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"数据有误",
		})
		return
	}
	var username string
	var password string
	var vir_type string
	if v,ok := c.GetPostForm("username");ok{
		username = v
	}
	if v,ok := c.GetPostForm("password");ok{
		password = v
	}
	if v,ok := c.GetPostForm("vir_type");ok{
		vir_type = v
	}
	uid := c.GetInt("uid")
	strUid := strconv.Itoa(uid)
	str ,err := zstack.Image.AddImage(string(byt),username,password,vir_type,strUid)
	if err != nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":err,
		})
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"操作成功",
		"data":str,
	})
}
/**
	添加镜像 回调
 */
func (t *image) CreateCallBack(c *gin.Context){

	byte,err := ioutil.ReadAll(c.Request.Body)
	if err != nil{
		fmt.Println(err)
		return
	}
	defer c.Request.Body.Close()

	//回调json结果转map
	m := map[string]interface{}{}
	err = json.Unmarshal(byte,&m)

	if err != nil {
		panic(err)
	}
	if m["error"] != nil{
		fmt.Println(m["error"].(map[string]interface{})["details"])
		return
	}
	username := c.Query("username")
	password := c.Query("password")
	vir_type := c.Query("vir_type")
	uid 	 := c.Query("uid")

	inventory := make(map[string]interface{})

	inventory = m["inventory"].(map[string]interface{})

	backupStorageRefs := make([]interface{},5)
	backupStorageRefs = inventory["backupStorageRefs"].([]interface{})

	inventory["backupStorageUuid"] = backupStorageRefs[0].(map[string]interface{})["backupStorageUuid"]
	inventory["installPath"] = backupStorageRefs[0].(map[string]interface{})["installPath"]

	delete(inventory,"backupStorageRefs")
	inventory["uid"] = uid
	inventory["system"] = strconv.FormatBool(inventory["system"].(bool))
	inventory["username"] = username
	inventory["password"] = password
	inventory["vir_type"] = vir_type
	err = service.Image.Create(inventory)
	if err != nil{
		fmt.Println(err)
		return
	}

}
func (t *image) Delete(c *gin.Context){

	uuid := c.Param("uuid")
	if uuid == ""{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"uuid有误，请重试",
		})
		return
	}
	w := map[string]interface{}{
		"uuid":uuid,
	}
	_, data := service.Image.First(w)

	bsuuid := data.BackupStorageUuid
	del_mod := "Permissive"

	result,err := zstack.Image.DelImage(uuid,bsuuid,del_mod)
	if err != nil{
		fmt.Println(err);
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"error",
		"data":result,
	})

}
func (t *image)DeleteCallBack(c *gin.Context){

	uuid := c.Query("uuid")
	if uuid == ""{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"uuid为空",
		})
		return
	}
	byte,err := ioutil.ReadAll(c.Request.Body)
	if err != nil{
		panic(err)
	}

	data := map[string]interface{}{}
	err = json.Unmarshal(byte,&data)

	if err != nil {
		panic(err)
	}
	if data["error"] != nil {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":data["error"].(map[string]interface{})["details"],
		})
		return
	}
	//软删除
	bool := service.Image.Delete(map[string]interface{}{"uuid":uuid})
	if bool{
		c.JSON(200,gin.H{
			"code":200,
			"msg":"error",
		})
		return
	}
}
// @Summary 镜像列表数据
// @Description Get JSON
// @Tags 镜像/images
// @Param enumerate query string false "搜索key uid|name|platform|vir_type"
// @Param search query string false "搜索value"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} util.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/images [get]
// @Security
func (t *image)Find(c *gin.Context){

	m := map[string]interface{}{}
	page,_ := strconv.Atoi(c.DefaultQuery("page","1"))
	pageSize := c.DefaultQuery("pageSize",strconv.FormatInt(util.Config.App.PageSize,10))
	NpageSize,_ := strconv.Atoi(pageSize)
	enumerate := c.Request.FormValue("enumerate")
	search := c.Request.FormValue("search")
	switch enumerate {
	case "uid":
		m["uid"] = search
	case "name":
		m["name"] = search
	case "platform":
		m["platform"] = search
	case "vir_type":
		m["vir_type"] = search
	}
	data,total,err := service.Image.Find(m,page,NpageSize)
	if err != nil {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"数据有误，请重试",
		})
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"操作成功",
		"data":data,
		"total":total,
	})

}
func (t *image)First(c *gin.Context){

	img_id := c.Param("img_id")
	if img_id == ""{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
		})
		return
	}
	bool,data := service.Image.First(map[string]interface{}{"img_id":img_id})
	if !bool {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
		})
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"操作成功",
		"data":data,
	})

}
func (t *image)ExpungeImage(c *gin.Context){

	uuid := ""
	body := ""
	zstack.Image.ExpungeImage(uuid,body)

}
func (t *image)Update(c *gin.Context){

	uuid := c.Param("uuid")
	if uuid == ""{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"参数：uuid不能为空",
		})
		return
	}

	d := make(map[string]map[string]interface{})
	d["updateImage"] = map[string]interface{}{}

	if v,ok := c.GetPostForm("name");ok{
		d["updateImage"]["name"] = v
	}
	/*
	if v,ok := c.GetPostForm("description");ok{
		d["updateImage"]["description"] = v
	}*/
	if v,ok := c.GetPostForm("mediaType");ok{
		d["updateImage"]["mediaType"] = v
	}
	if v,ok := c.GetPostForm("format");ok{
		d["updateImage"]["format"] = v
	}
	if v,ok := c.GetPostForm("system");ok{
		d["updateImage"]["system"] = v
	}
	if v,ok := c.GetPostForm("platform");ok{
		d["updateImage"]["platform"] = v
	}
	if v,ok := c.GetPostForm("description");ok{
		d["updateImage"]["description"] = v
	}
	var username string
	var password string
	var vir_type string

	if v,ok := c.GetPostForm("username");ok{
		username = v
	}
	if v,ok := c.GetPostForm("password");ok{
		password = v
	}
	if v,ok := c.GetPostForm("vir_type");ok{
		vir_type = v
	}
	byte,_ := json.Marshal(d)
	str,err := zstack.Image.UpdateImage(uuid,string(byte),username,password,vir_type)
	if err != nil{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":"数据有误，请重试",
		})
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"操作成功",
		"data":str,
	})

}
/**
	更新镜像回调方法
 */
func (t *image)UpdateCallBack(c *gin.Context){

	str,err := ioutil.ReadAll(c.Request.Body)
	defer c.Request.Body.Close()

	if err != nil {
		panic(err)
	}

	username := c.Query("username")
	password := c.Query("password")
	vir_type := c.Query("vir_type")

	data := make(map[string]interface{})
	err = json.Unmarshal(str,&data)

	inv := make(map[string]interface{})
	inv = data["inventory"].(map[string]interface{})
	inv["username"] = username
	inv["password"] = password
	inv["vir_type"] = vir_type

	uuid := inv["uuid"].(string)

	delete(inv,"uuid")
	if err != nil {
		panic(err)
	}

	bool := service.Image.Update(uuid,inv)
	if !bool{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
		})
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"操作成功",
	})

}

var Image = &image{}